﻿using System;
using System.IO;
using System.Xml.Serialization;


namespace FenixAdar.Xml
{
    /// <summary>
    /// XML文件序列化与反序列化
    /// </summary>
    public class XmlManager
    {       
        /// <summary>
        /// 将XML文件反序列化成预先定义好的对应的类
        /// </summary>
        /// <typeparam name="T">预先定义好的对应的类的类型</typeparam>
        /// <param name="xmlLoadPath">将要反序列化的XML文件地址</param>
        /// <returns>反序列化后的类的实例</returns>
        public T Deserialize<T>(string xmlLoadPath)
        {
            XmlSerializer xs = null;
            try
            {
                xs = new XmlSerializer(typeof(T));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            Stream stream = new FileStream(xmlLoadPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            T t = default(T);
            try
            {
                t = (T)xs.Deserialize(stream);
            }
            finally
            {
                stream.Close();
            }

            return t;
        }

        /// <summary>
        /// 将可序列化的类序列化成XML文件
        /// </summary>
        /// <typeparam name="T">要序列化的类的类型</typeparam>
        /// <param name="xmlSavePath">序列化后的XML文件保存地址</param>
        /// <param name="t">要序列化的类的实例</param>
        public void Serialiaze<T>(string xmlSavePath, T t)
        {            
            XmlSerializer xs = new XmlSerializer(typeof(T));
            Stream stream = new FileStream(xmlSavePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            
            try
            {
                xs.Serialize(stream, t);
            }
            finally
            {
                stream.Close();
            }
        }        
    }
        

}
